// request.js

import axios from 'axios'
//const baseurl = 'http://127.0.0.1:2346/'
const baseurl = 'http://localhost:3000/api'

const request = axios.create({
  baseURL: baseurl, //'http://thinktest', // 设置请求的baseURL
  withCredentials: true,
  timeout: 5000 // 设置请求超时时间
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    // 可以在发送请求前进行一些处理，例如添加token等
    let token = localStorage.getItem('token')
    if (token) {
      config.headers['authorization'] = token
    }
    return config
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    // 可以在获取到响应后进行一些处理，例如处理错误码等
    let token = response.headers.authorization
    if (token) {
      localStorage.setItem('token', token)
    }
    return response
  },
  (error) => {
    // 对响应错误做点什么
    return Promise.reject(error)
  }
)
// 封装 GET POST 请求并导出query
export function require(url = '', params = {}, type = 'GET') {
  //设置 url params type 的默认值
  return new Promise((resolve, reject) => {
    let promise
    if (type.toUpperCase() === 'GET') {
      promise = request({
        url,
        params
      })
    } else if (type.toUpperCase() === 'POST') {
      promise = request({
        method: 'POST',
        url,
        data: params
      })
    }
    //处理返回
    promise
      .then((res) => {
        resolve(res)
      })
      .catch((err) => {
        reject(err)
      })
  })
}
export function query(url = '', params = {}) {
  return new Promise((resolve) => {
    request({ method: 'GET', url, params })
      .then((res) => {
        resolve(res)
      })
      .catch((reason) => {
        console.log(reason)
      })
  })
}
export function report(url = '', params = {}) {
  return new Promise((resolve) => {
    request({ method: 'POST', url, data: params })
      .then((res) => {
        resolve(res)
      })
      .catch((reason) => {
        console.log(reason)
      })
  })
}
export async function get(url = '', params = {}) {
  try {
    return await request.get(url, params)
  } catch (err) {
    throw err.message
  }
}
request.sending = (url = '', params = {}, type = 'POST') => {
  return new Promise((resolve, reject) => {
    request({ method: type, url, data: params })
      .then((res) => {
        var result = { type: 'success', data: {}, info: res }
        if (res.status == 200) result.data = res.data
        else if (res.status == 300) result.type = 'redirect'
        else result.type = 'error'
        resolve(result)
      })
      .catch((reason) => {
        console.log(reason)
        reject(reason)
      })
  })
}
export default request
